package com.mobilezu.mobile.pushserver.console.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.mobilezu.mobile.pushserver.util.Config;
import com.mobilezu.mobile.pushserver.util.Constants;
import com.mobilezu.mobile.pushserver.xmpp.push.NotificationManager;


public class PushBroadcastController extends MultiActionController {

	private NotificationManager notificationManager;

	public PushBroadcastController() {
		notificationManager = new NotificationManager();
	}

	public ModelAndView list(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("notification/push_form");
		return mav;
	}

	/**
	 * ��webҳ��������Ϣ
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView send(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String broadcast = ServletRequestUtils.getStringParameter(request,
				"broadcast1", "N");
		String usernames = ServletRequestUtils.getStringParameter(request,
				"username").trim();

		HttpSession session = request.getSession(true);
		String sendUsername = (String) session.getAttribute("adusername");
		String sendName = (String) session.getAttribute("adname");
		String message = Constants.subString(ServletRequestUtils
				.getStringParameter(request, "message").trim(), 1000);

		String uri = Constants.subString(
				ServletRequestUtils.getStringParameter(request, "uri"), 500);

		String apiKey = Config.getString("apiKey", "");

		if (broadcast.equalsIgnoreCase("N")) {
			notificationManager.webSendToSomeUsers(apiKey, sendUsername,
					sendName, usernames, message, uri);
		} else if (broadcast.equalsIgnoreCase("O")) {
			notificationManager.sendToOnlineUsers(apiKey, sendUsername,
					sendName, message, uri);
		} else if (broadcast.equalsIgnoreCase("Y")) {
			notificationManager.sendToAllUsers(apiKey, sendUsername, sendName,
					message, uri);
		}

		ModelAndView mav = new ModelAndView();
		mav.setViewName("redirect:push_broadcast.do");
		return mav;
	}

}
